package com.hotel.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.commontools.data.DataTool;
import com.hotel.util.RedisSessionUtil;
import com.hotel.util.ResultCode;

public class HttpRequestTokenInterceptor implements HandlerInterceptor {
	@Resource
	private RedisSessionUtil redisSessionUtil;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		response.setContentType("text/html;charset=UTF-8");
		try {
			String access_token = (String) request.getHeader("access_token");
			System.out.println("access_token==>>>" + access_token);
			if (access_token == null) {
				System.out.println("000");
				response.getWriter().write(DataTool.constructResponse(
								ResultCode.ACCESS_TOKEN_ERROR,
								"access_token错误", null));
				return false;
			} else {

				System.out.println("111");
				List<String> priviliegeList = (List<String>) redisSessionUtil
						.getSession(access_token);
				if (priviliegeList == null) {
					System.out.println("222");
					response.getWriter().write(DataTool
									.constructResponse(
											ResultCode.ACCESS_TOKEN_ERROR,
											"access_token错误", null));
					return false;
				} else {
					return true;
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("333");
			// TODO: handle exception
			response.getWriter().write(DataTool.constructResponse(
							ResultCode.ACCESS_TOKEN_ERROR, "access_token错误",
							null));
			return false;
		}

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
